import redis
import sys
import time
from db import ObjLink
import multiprocessing


#任务处理
def task(info):
    if info['action'] == 'ceshi':
        print('只是测试')
        #解析info信息
        client = info['client']
        message = ""
        redis.publish(client,message)
    else:
        print("nothing")

if __name__== '__main__':
    redis = ObjLink.getRedisDB()

    consumer_name = "client"
    stream_name = "stream"
    group_name = "stream-group"

    if redis.exists(stream_name):
        redis.delete(stream_name)

    #action:任务目标，ceshi是默认行为,client，提交数据的客户标识，任务完成以后会吧数据返回给clientid,并推送数据id
    r1 = redis.xadd(stream_name, {'action':'ceshi', 'client':'clientid'})

    redis.xgroup_create(stream_name, group_name, id=0)  # 0 从开始消费, $ 从尾部消费
    print("stream info is :", redis.xinfo_stream(stream_name))
    print("groups info is :", redis.xinfo_groups(stream_name))

    #创建进程池
    pool = multiprocessing.Pool(processes = 12)

    while True:
        #按插入顺序获取
        items = redis.xreadgroup(group_name, consumer_name, {stream_name: '>'}, block=0, count=1)
        #解析数据
        id = items[0][1][0][0]
        info = items[0][1][0][1]
        #创建任务
        pool.apply_async(task, (info, ))

        redis.xack(stream_name, group_name, id)  #前面pending 是1,ack以后是0
        redis.xdel(stream_name, id)  #删除掉处理的

